package com.cn.longdistancebusstation.contacter;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.adapter.SelectPassengersAdapter;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.callback.OnCustomViewClickListener;
import com.cn.longdistancebusstation.callback.OnSelectPassengerTypeListener;
import com.cn.longdistancebusstation.global.GlobalVariable;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.Contacter;
import com.cn.longdistancebusstation.model.ListResult;
import com.cn.longdistancebusstation.order.ConfirmOrderActivity;
import com.cn.longdistancebusstation.view.SelectPassengersListView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * 乘客列表
 * Created by mucheng on 2018/1/27.
 */

public class PassengerListActivity extends BaseActivity implements OnSelectPassengerTypeListener, View.OnClickListener,AdapterView.OnItemClickListener, OnCustomViewClickListener{
    private LinearLayout mAddPassengersLinearLayout;
    private SelectPassengersListView mSelectPassengersListView;
    private Button btn_sure;
    private ArrayList<Contacter> mContacterList =new ArrayList<>();
    //从确认订单界面传回来的
    private ArrayList<Contacter> mPreChooseContacterList = new ArrayList<>();
    private SelectPassengersAdapter mAdapter;
    private Boolean mStateBoolean;
    private int mPosition;
    private ScrollView mScrollView;
    private RelativeLayout mRelativeLayout;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_passengers);
        getTitleTextView().setText("选择乘车人");
        //
        Intent intent = getIntent();
        mPreChooseContacterList = (ArrayList<Contacter>) intent.getSerializableExtra("data");
        //
        initView();
    }

    private void initView() {
        mAddPassengersLinearLayout=(LinearLayout)findViewById(R.id.add_new_passengers);
        mAddPassengersLinearLayout.setOnClickListener(this);
        btn_sure=(Button)findViewById(R.id.sure);
        btn_sure.setOnClickListener(this);
        mSelectPassengersListView=(SelectPassengersListView)findViewById(R.id.list_select_pessengers);
        mAdapter =new SelectPassengersAdapter(this, mContacterList);
        mSelectPassengersListView.setAdapter(mAdapter);
        mAdapter.setOnCustomViewClickListener(this);
        mAdapter.setOnSelectPassengerTypeListener(this);
        mSelectPassengersListView.setChoiceMode(SelectPassengersListView.CHOICE_MODE_MULTIPLE);
        mSelectPassengersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                SelectPassengersAdapter.ViewHolder holder=(SelectPassengersAdapter.ViewHolder)view.getTag();
                //在每次获取点击的item时将对于的checkbox状态改变，同时修改map的值
                holder.mCheckbox.toggle();
                mStateBoolean=SelectPassengersAdapter.isSelected.put(i, holder.mCheckbox.isChecked());
            }
//                Intent intent=new Intent(PassengerListActivity.this,ConfirmOrderActivity.class);


        });

        mSelectPassengersListView.setAdapter(mAdapter);
        mScrollView=(ScrollView)findViewById(R.id.scrollView);
        mRelativeLayout=(RelativeLayout)findViewById(R.id.child_layout);
        getPassengers();
    }

    private void getPassengers() {
        mContacterList.clear();
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService=retrofit.create(HttpService.class);
        Call<ListResult<Contacter>> call=httpService.getCommonContacts(GlobalVariable.getUserID());
        showHud();
        call.enqueue(new Callback<ListResult<Contacter>>() {
            @Override
            public void onResponse(Call<ListResult<Contacter>> call, Response<ListResult<Contacter>> response) {
                hideHud();
                ListResult result=response.body();
                Gson gson=new Gson();
                String strbody=gson.toJson(result.getBody().getData());
                Log.d("乘车人员",strbody);
                Type listtype=new TypeToken<List<Contacter>>(){}.getType();
                mContacterList =gson.fromJson(strbody,listtype);
                if(mPreChooseContacterList.size() > 0){
                    for(Contacter contacter : mContacterList){
                        for(int i=0; i<mPreChooseContacterList.size(); i++){
                            Contacter tempContacter = mPreChooseContacterList.get(i);
                            if(contacter.getId().equals(tempContacter.getId())){
                                contacter.setChoose(tempContacter.getChoose());
                                contacter.setType(tempContacter.getType());
                                contacter.setPayInsurance(tempContacter.getPayInsurance());
                            }
                            else{
                                continue;
                            }
                        }
                    }
                }
                mAdapter.setDataSourceList(mContacterList);
//                mAdapter =new SelectPassengersAdapter(PassengerListActivity.this, mContacterList);
//                list.setAdapter(mAdapter);
                mAdapter.notifyDataSetChanged();
                if(mContacterList.size()==0){
                    mRelativeLayout.setVisibility(View.VISIBLE);
                    mScrollView.setVisibility(View.GONE);
                }else{
                    mRelativeLayout.setVisibility(View.GONE);
                    mScrollView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(Call<ListResult<Contacter>> call, Throwable t) {

            }
        });
    }

    private void showPassengerType(int type) {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_linkman_type, null);
        final TextView tv_adult = (TextView) view.findViewById(R.id.tv_adult);
        final TextView tv_child = (TextView) view.findViewById(R.id.tv_child);
        final TextView tv_student = (TextView) view.findViewById(R.id.tv_student);
        final TextView tv_soldier = (TextView) view.findViewById(R.id.tv_soldier);
        TextView btnCancel = (TextView) view.findViewById(R.id.btn_cancel);
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
        popupWindow.setOutsideTouchable(true);
        View parent = LayoutInflater.from(this).inflate(R.layout.activity_add_new_passengers, null);
        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        //popupWindow在弹窗的时候背景半透明
        final WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                params.alpha = 1.0f;
                getWindow().setAttributes(params);
            }
        });
        tv_adult.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Contacter contacter=mContacterList.get(mPosition);
                contacter.setType(0);
                mAdapter.notifyDataSetChanged();
                popupWindow.dismiss();
            }
        });
        tv_child.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Contacter contacter=mContacterList.get(mPosition);
                contacter.setType(1);
                mAdapter.notifyDataSetChanged();
                popupWindow.dismiss();

            }
        });
        tv_student.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Contacter contacter=mContacterList.get(mPosition);
                contacter.setType(2);
                mAdapter.notifyDataSetChanged();
                popupWindow.dismiss();

            }
        });
        tv_soldier.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Contacter contacter=mContacterList.get(mPosition);
                contacter.setType(3);
                mAdapter.notifyDataSetChanged();
                popupWindow.dismiss();

            }
        });


        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.add_new_passengers:
                Intent in=new Intent(PassengerListActivity.this,AddNewPassengersActivity.class);
                startActivity(in);
                break;
            case R.id.sure:
                Intent intent=new Intent(PassengerListActivity.this,ConfirmOrderActivity.class);
                List<Contacter> contacterList = new ArrayList<>();
                for(int i=0; i<mContacterList.size(); i++){
                    Contacter contacter = mContacterList.get(i);
                    if(contacter.getChoose()){
                        contacterList.add(contacter);
                    }
                }
                intent.putExtra("contacter", (Serializable)contacterList);
                setResult(RESULT_OK, intent);
                finish();
                break;
        }

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

    }
    @Override
    protected void onResume() {
        super.onResume();
        getPassengers();
    }

    @Override
    public void onClick() {
        //显示保险说明
        Intent intent = new Intent(PassengerListActivity.this, InsuranceDescActivity.class);
        startActivity(intent);
    }

    @Override
    public void onClickType(int position) {
//        Contacter contacter=mContacterList.get(position);
//        mPosition=position;
//        showPassengerType(contacter.getType());

    }
}
